import { useState } from 'react'
import {
  ProCard,
  PageLoading
} from '@ant-design/pro-components';
import {
  Tabs,
  Input,
  Avatar,
  Space,
  message,
  Button,
} from 'antd'
import type { TabsProps } from 'antd';
import classnames from 'classnames';
import Camera from '@/components/Camera'
import PatientList from '@/components/PatientList'
import PulseInfo from '@/components/PulseInfo';
import IllnessList from '@/components/IllnessList'
import QuestionTerm from '@/components/QuestionTerm'
import defImg from '@/static/images/header.png';

import { genderSchema, patientStatusSchema } from '@/utils/schema'
import { arrayFormatObj } from '@/utils'

import {
  reqDetal,
  reqUpdate,
} from '@/services/basicConsultation';

import styles from './index.module.less'
import BasicPatientList from '@/components/BasicPatientList';

const Id = () => {

  const [loading, setLoading] = useState(false)

  // 患者搜索字段
  const [searchKey, setSearchKey] = useState('')

  // 当前问诊用户
  const [user, setUser] = useState<any>(null)

  // 当前用户问诊详情数据
  const [medicalCase, setMedicalCase] = useState<any>(null)

  const [item, setItem] = useState<any>(null);


  const [update, setUpdate] = useState(0)

  console.log('当前用户问诊详情数据 :>> ', medicalCase);

  const onChange = (key: string) => {
    console.log(key);
  };


  const readonly = user?.status == 3;

  const items: TabsProps['items'] = [
    {
      key: '0',
      label: '问诊项目',
      disabled: true,
      // children: '问诊项目',
    },
    {
      key: '1',
      label: '脉诊',
      children: <PulseInfo user={medicalCase} />,
    },
    {
      key: '2',
      label: '舌诊',
      children:
        <Camera
          onChangeImage={(tonguePic: string) => upDataInfo({ tonguePic })}
          initSrc={medicalCase?.tonguePic}
          noClose
          isEdit={!readonly}
        />,
    },
    {
      key: '3',
      label: '基本问诊',
      children:
        <QuestionTerm
          user={medicalCase}
          upDataInfo={upDataInfo}
          readonly={readonly}
        />,
    },
    {
      key: '4',
      label: '检测报告拍摄',
      children:
        <Camera
          onChangeImage={(reportPic: string) => upDataInfo({ reportPic })}
          initSrc={medicalCase?.reportPic}
          noClose
          isEdit={!readonly}
        />,
    },
    {
      key: '5',
      label: '输入病史',
      children: <IllnessList readonly={readonly} user={medicalCase} upDataInfo={upDataInfo} />,
    },
  ];


  // 选择问诊用户
  async function onSelectList(item: any) {
    setLoading(true)
    await getDetal(item?.id)
    setUser(item)
    setLoading(false)
  }

  const listItems = [
    {
      key: '1',
      label: '待就诊',
      children:
        <BasicPatientList
          status=''
          type='1'
          update={update}
          searchKey={searchKey}
          onSelect={(item: any) => onSelectList(item)}
          onPush={onSubmit}
          user={user}
        />
      ,
    }
  ];


  // 病历信息详情(基础+高级问诊)
  async function getDetal(id: number | string) {
    try {
      const res = await reqDetal({
        id
      })
      console.log('病历信息详情 :>> ', res?.data);
      if (res?.resultCode == '00000000') {

        // setData(res?.data?.result)
        setMedicalCase(res?.data)
      } else {
        message.error(`病历信息详情出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('病历信息详情出错！', error)
      console.log('病历信息详情出错！ :>> ', error);
    }
  }

  // 更改问诊信息
  async function upDataInfo(params: object) {

    try {
      const res = await reqUpdate({
        id: medicalCase?.id,
        illnessNameHistory: medicalCase?.illnessNameHistory,
        basicInquiryJson: medicalCase?.basicInquiryJson,
        tonguePic: medicalCase?.tonguePic,
        reportPic: medicalCase?.reportPic,
        medicalHistory: medicalCase?.medicalHistory,
        status: medicalCase?.status,
        ...params
      })

      console.log('更改问诊信息信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        // setData(res?.data?.result)
        medicalCase?.id && await getDetal(medicalCase?.id)
        message.success(`更改问诊信息成功`)
      } else {
        message.error(`病种病名列表信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('病种病名列表信息出错！', error)
      console.log('病种病名列表信息出错！ :>> ', error);
    }
  }

  // 搜索患者列表
  function onSearchSelect(value: string) {
    console.log('onSearchSelect=== :>> ', value);
    setSearchKey(value)
  }

  // 提交到医生
  async function onSubmit(item: any) {
    // 获取当前用户信息
    const userData = await reqDetal({
      id: item?.id
    })
    if(!userData?.data?.tabooMedication || !userData?.data?.previouslyUsedMedication || !userData?.data?.medicalHistory){
      message.warning('请输入问诊信息');
      return;
    }

    await upDataInfo({
      id: item?.id,
      illnessNameHistory: userData?.data?.illnessNameHistory,
      basicInquiryJson: userData?.data?.basicInquiryJson,
      tonguePic: userData?.data?.tonguePic,
      reportPic: userData?.data?.reportPic,
      medicalHistory: userData?.data?.medicalHistory,
      status: 3
    });
    setSearchKey('')
    setUser(null)
    setUpdate(prv => prv + 1)
  };

  const sexObj = arrayFormatObj(genderSchema.options);

  const patientStatus = arrayFormatObj(patientStatusSchema.options);
  // console.log('sexObj :>> ', user?.gender, (user?.gender || user?.gender == 0) && sexObj[user?.gender]?.label);

  return (
    <div className={styles.main}>
      { !user ?
      <div className={styles.left}>
        {/* <AutoComplete
            // popupMatchSelectWidth={252}
           
            options={options}
            onSelect={onSearchSelect}
            onSearch={handleSearch}
          > */}
        <Input.Search
          size="large"
          style={{ width: '100%' }}
          placeholder="患者姓名/手机号/身份证号码"
          enterButton='查询'
          onSearch={onSearchSelect}
          onPressEnter={(e) => onSearchSelect(e?.target?.value)}
        />
        <Tabs
          defaultActiveKey=""
          items={listItems}

          onChange={() => setUpdate(prev => prev + 1)}
        />
      </div>
      :null}
      <div className={styles.right}>
        {
          user ?
            <>
              <div className={styles.userBox}>
                <Space size={16}
                  direction="vertical"
                  className={classnames(styles.commonMar, styles.userWrap)}
                >
                  <Space size={16}>
                    <Avatar
                      size={{ xs: 32, sm: 32, md: 54, lg: 54, xl: 54, xxl: 54 }}
                      src={user?.avatar || defImg}
                    />
                    <Space direction="vertical">
                      <div>姓名:{user?.tyPatientName}</div>
                      <div>性别:{(user?.gender || user?.gender == 0) && sexObj[user?.gender]?.label}</div>
                    </Space>
                  </Space>
                  <div>
                    <Space size={24}>
                      {/* <div>所属团队:张四</div> */}
                      <div>手机: {user?.phoneNum}</div>
                      <div>身份证号:{user?.cardId}</div>
                      <div>预约时间:{user?.appointTime}</div>
                      {/* <div>就诊状态:{user?.status && patientStatus[user?.status]?.label}</div> */}
                      <div><Button size='small' type='primary' onClick={()=>{setUser(null)}}>返回</Button></div>
                      <div><Button size='small' type='primary' onClick={()=>{onSubmit(user)}}>提交到医生</Button></div>
                    </Space>
                  </div>
                </Space>
              </div>
              <div style={{overflowY:'auto',display:'flex',flexDirection:'row',flexWrap:'wrap'}} className={styles.hushiwenzhen}>
                <div className={styles.userInfoWrap}>
                  <div className={styles.userInfo}>
                    <PulseInfo user={medicalCase} />
                  </div>
                </div>
                <div className={styles.userInfoWrap}>
                  <div className={styles.userInfo}>
                  <Camera
                    onChangeImage={(tonguePic: string) => upDataInfo({ tonguePic })}
                    initSrc={medicalCase?.tonguePic}
                    title='舌诊'
                    noClose
                    isEdit={!readonly}
                  />
                  </div>
                </div>
                {/* <div className={styles.userInfoWrap}>
                  <div className={styles.userInfo}>
                  <QuestionTerm
                    user={medicalCase}
                    upDataInfo={upDataInfo}
                    readonly={readonly}
                  />
                  </div>
                </div> */}
                <div className={styles.userInfoWrap}>
                  <div className={styles.userInfo}>
                  <Camera
                    onChangeImage={(reportPic: string) => upDataInfo({ reportPic })}
                    initSrc={medicalCase?.reportPic}
                    title='检测报告'
                    noClose
                    isEdit={!readonly}
                  />
                  </div>
                </div>
                <div className={styles.userInfoWrap}>
                  <div className={styles.userInfo}>
                  <IllnessList readonly={readonly} user={medicalCase} upDataInfo={upDataInfo} />
                  </div>
                </div>
              </div>

              {/* <div className={styles.cententWrap}>
                {
                  !loading ?
                    <Tabs
                      className={styles.greenBg}
                      defaultActiveKey="1"
                      items={items}
                      onChange={onChange}
                      tabPosition="right"
                    />
                    :
                    <PageLoading />
                }
              </div> */}
            </>
            :
            <></>
        }
      </div>
    </div>
  )
}

export default Id